import { load } from "/web/util/LoadView.js";
load('newscenter');
let newslist = []
//搜索新闻，需要后端支持，根据标题模糊查询
// search.oninput = async function (){
//     if(!search.value){
//         searchlist.style.display = 'none'
//         return
//     }
//     searchlist.style.display = 'block'
//     console.log(search.value)
//     let res = await fetch(`http://localhost:3000/news?title_like=${search.value}`).then(res=>res.json())
//     document.querySelector('.list-group').innerHTML = res.map(item =>`
//         <li class="list-group-item">${item.title}</li>
//     `).join('')

// }
// search.onblur = function(){
//     setTimeout(()=>{
//         searchlist.style.display = 'none'
//     },300)
// }

let renderLatestNews = async function(){
    let res = await fetch('http://localhost:3000/news').then(res=>res.json())
    newslist = res
    newslist.reverse()
    let latestnewslist = newslist.slice(0,4)
    document.querySelector('.latestnews').innerHTML = latestnewslist?.map(item =>`
        <div class="card cardsty1" style="width: 100%;" data-id="${item.id}">
            <div class="card-img-top cardimg" style="background-image:url(${item.cover})"></div>
            <div class="card-body">
                <h5 class="card-title" style="font-size: 16px;">${item.title}</h5>
                <p class="card-text" style="font-size:14px;color:gray">作者:${item.author}</p>
            </div>
        </div>
    `).join('') || ''
    for(let item of document.querySelectorAll('.card')){
        item.onclick = function(){
            location.href = `/web/views/detail/index.html?id=${item.dataset.id}`
        }
    }
}

let renderBottomNews = function(){
    let res = _.groupBy(newslist,item => item.category)
    // console.log(res)
    //重点
    let tabs = [tab0,tab1,tab2]//tab0,tab1,tab2是三个id节点
    tabs.forEach((item,index)=>{
        item.innerHTML = res[index]?.map(item =>`
        <div class="card cardsty2" data-id="${item.id}">
            <div class="card-img-top cardimg" data-id="${item.id}" style="background-image: url(${item.cover});"></div>
            <div class="card-body" data-id="${item.id}">
                <h5 class="card-title" data-id="${item.id}">${item.title}</h5>
                <p class="card-text" data-id="${item.id}">作者id:${item.author}</p>
            </div>
        </div>
        `).join('') || ''
        item.onclick = function(evt){
            // console.log(111,evt.target.dataset.id)
            location.href = `/web/views/detail/index.html?id=${evt.target.dataset.id}`
        }
    })
}

async function render(){
    await renderLatestNews()
    renderBottomNews()
}
render()